<template>
  <div class="com-container">
    <div class="com-chart" ref="stock_ref"></div>
  </div>
</template>

<script setup lang="ts">
import { getCurrentInstance, ref, onMounted, onUnmounted } from "vue";
import axios from "axios";
import { getThemeValue } from "@/utils/theme_utils.ts";
import { useThemeChart } from "@/hooks/useThemeChart.ts";

const { proxy } = getCurrentInstance()!;
const stock_ref = ref();
const allData = ref([]);
const echartsInstance = ref(null);
const currentIndex = ref(0);
const timerId = ref(null);

// 初始化echartsInstance对象
const initChart = () => {
  echartsInstance.value = proxy!.$echarts.init(stock_ref.value, themeStore.theme);
  // 对图表初始化配置的控制
  const initOption = {
    title: {
      text: "▎库存和销量分析",
      left: 20,
      top: 20
    },
    backgroundColor: getThemeValue(themeStore.theme).bgColor
  };
  echartsInstance.value.setOption(initOption);
  // 对图表对象进行鼠标事件的监听
  echartsInstance.value.on("mouseover", () => {
    clearInterval(timerId.value);
  });
  echartsInstance.value.on("mouseout", () => {
    startInterval();
  });
};

// 获取服务器的数据
const getData = async () => {
  const { data: res } = await axios.get("http://127.0.0.1:8888/api/stock");
  allData.value = res;
  updateChart();
  // 启动定时器
  startInterval();
};

// 更新图表
const updateChart = () => {
  const centerArr = [
    ["18%", "40%"],
    ["50%", "40%"],
    ["82%", "40%"],
    ["34%", "75%"],
    ["66%", "75%"]
  ];
  const colorArr = [
    ["#4FF778", "#0BA82C"],
    ["#E5DD45", "#E8B11C"],
    ["#E8821C", "#E55445"],
    ["#5052EE", "#AB6EE5"],
    ["#23E5E5", "#2E72BF"]
  ];
  // 处理图表需要的数据
  const start = currentIndex.value * 5;
  const end = (currentIndex.value + 1) * 5;
  const showData = allData.value.slice(start, end);
  const seriesArr = showData.map((item, index) => {
    return {
      type: "pie",
      center: centerArr[index],
      emphasis: {
        scale: false
      },
      labelLine: {
        show: false // 隐藏指示线
      },
      data: [
        {
          label: {
            show: true,
            position: "center",
            color: colorArr[index][0]
          },
          name: item.name + "\n" + item.sales,
          value: item.sales,
          itemStyle: {
            show: true,
            color: new proxy!.$echarts.graphic.LinearGradient(0, 1, 0, 0, [
              {
                offset: 0,
                color: colorArr[index][0]
              },
              {
                offset: 1,
                color: colorArr[index][1]
              }
            ])
          }
        },
        {
          value: item.stock,
          itemStyle: {
            // color: "#333843"
            color: getThemeValue(themeStore.theme).labelColor
          }
        }
      ]
    };
  });
  const dataOption = {
    series: seriesArr
  };
  echartsInstance.value.setOption(dataOption);
};

const startInterval = () => {
  if (timerId.value) {
    clearInterval(timerId.value);
  }
  timerId.value = window.setInterval(() => {
    currentIndex.value++;
    if (currentIndex.value > 1) {
      currentIndex.value = 0;
    }
    updateChart();
  }, 3000);
};

const screenAdapter = () => {
  const titleFontSize = (stock_ref.value.offsetWidth / 100) * 3.6;
  const adapterOption = {
    title: {
      textStyle: { fontSize: titleFontSize }
    },
    series: Array(5).fill({
      // 动态生成系列配置
      type: "pie",
      radius: [titleFontSize * 2.25, titleFontSize * 2],
      label: { fontSize: titleFontSize / 2 }
    })
  };
  echartsInstance.value.setOption(adapterOption);
  // 手动的调用图表对象的resize 才能产生效果
  echartsInstance.value.resize();
};

const { themeStore } = useThemeChart(echartsInstance, initChart, updateChart, screenAdapter);

onMounted(() => {
  // 注册回调（使用可选链操作符）
  proxy.$socket.registerCallBack("stockData", getData);
  initChart();
  proxy.$socket.send({
    action: "getData",
    socketType: "stockData",
    chartName: "stock",
    value: ""
  });
  window.addEventListener("resize", screenAdapter);
  // 在页面加载完成的时候, 主动进行屏幕的适配
  screenAdapter();
});

onUnmounted(() => {
  if (timerId.value) {
    clearInterval(timerId.value);
  }
  // 在组件销毁的时候, 需要将监听器取消掉
  window.removeEventListener("resize", screenAdapter);
  // 注销回调（使用可选链操作符）
  proxy.$socket.unRegisterCallBack("stockData");
});

defineExpose({
  screenAdapter
});
</script>
